<template>
    <div class="boxs-bov">
      <div class="top_some">
        <el-icon class="icons" @click="searchMore"><Expand /></el-icon>
        <el-input
          v-model.trim="formInline.school_name"
          placeholder="学校名称"
          style="width: 100%"
          clearable
          @clear="search"
        ></el-input>
        <el-button type="primary" @click="search">搜索</el-button>
      </div>
      <div class="multiple_choice" v-if="choices">
        <!-- 多选操作 -->
        <el-checkbox v-model="checked1" @change="change1">全选</el-checkbox>
        <el-link type="primary" @click="CloseManage"
          ><el-icon><CloseBold /></el-icon>关闭管理</el-link
        >
      </div>
  
      <div v-if="tableData.length > 0">
        <div v-for="(item, index) in tableData" :key="index">
          <shoolcol
            :choices="choices"
            :dataobjs="item"
            :is_operation='authority([2,4])'
            @inspect="inspect"
            ref="multipleTable"
            @handleEdit="handleEdit"
            @openOkAllons="openOkAllons"
          ></shoolcol>
        </div>
      </div>
      <div v-else>
        <el-empty description="暂无数据" />
      </div>
      <div style="height: 2vh"></div>
  
      <Pagination
        v-if="tableData.length > 0&&!choices"
        v-bind:child-msg="pageparm"
        @callFather="callFather"
      ></Pagination>
  
      <div style="height: 10vh"></div>
  
      <!-- 组件 -->
      <!-- <H5ShoolDialog ref="RefScreen" :dialogVisible="searchMoreType" @refreshData="searchMore()" @handleEdit="handleEdit('', 'reset')" @search="search"></H5ShoolDialog> -->
  
      <ly-dialog
        :model-value="searchMoreType"
        :destroyClose="false"
        :title="'搜索'"
        width="560px"
        :before-close="searchMore"
      >
        <screen ref="RefScreen" :formInline="formInline" :inline="false"></screen>
        <template #footer>
          <el-button @click="searchMore">取消</el-button>
          <el-button @click="handleEdit('', 'reset')" icon="Refresh"
            >重置</el-button
          >
          <el-button type="primary" icon="Search" @click="search">查询</el-button>
        </template>
      </ly-dialog>
      <!-- 底部操作 -->
      <BottomAdd  v-if="tableData.length > 0&&authority([2,4])">
        <div class="boxs_bov_buttons" v-if="!choices">
           
          <el-button
            :icon="`Promotion`"
            style="width: 100%; height: 40px"
            @click="choices = true"
            >管理</el-button
          >
        </div>
        <div class="boxs_bov_buttons" v-if="choices">
          <el-button
            @click="openOkAll"
            style="width: 100%; height: 40px"
            v-if="authority([2])"
            >批量重新核校</el-button
          >
          <el-button
            v-if="authority([1, 2])"
            type="danger"
            @click="handleDelete"
            style="width: 100%; height: 40px"
            >批量删除</el-button
          >
          <el-button
            @click="openOkAll"
            style="width: 100%; height: 40px"
            v-if="authority([4])"
            >批量重新核校</el-button
          >
        </div>
      </BottomAdd>
      <!-- 在地区域管理员操作 -->
      <addModuleShool ref="addModuleShool" @refreshData="refreshData">
      </addModuleShool>
    </div>
  </template>
  
  <script>
  import LyDialog from "@/components/dialog/dialog.vue";
  import shoolcol from "@/components/shoolcol.vue";
  import BottomAdd from "@/components/bottom_add.vue";
  
  import Pagination from "@/components/Pagination.vue";
  import { dateFormats } from "@/utils/util";
  import "video.js/dist/video-js.css";
  import {
    schoolList,
    schoolDel,
    adminGroup,
    schoolImport,
    rstaffschoolAdd,
    addschool,
    schoolExport,
    schoolEdit,
    statuss,
  } from "@/api/api";
  import XEUtils from "xe-utils";
  // import AddModuleGoodsType from "./components/add.vue"; //普通新增
  // import addModuleShool from "./components/addShool.vue";
  // import editModuleShool from "./components/editShool.vue";
  import screen from "@/components/screen/screen.vue";
  import addModuleShool from "../components/noAddShool.vue"; //在地和在地区域的新增
  
  import { lyMixins } from "@/mixins/mixins";
  import dayjs from "dayjs";
  import { setStorage, getStorage } from "@/utils/util";
  import axios from "axios";
  import { saveAs } from "file-saver";
  import ExcelJS from "exceljs";
  export default {
    mixins: [lyMixins],
    components: {
      Pagination,
      screen,
      LyDialog,
      shoolcol,
      BottomAdd,
      addModuleShool
    },
    name: "adminManage",
    data() {
      return {
        checked1: false, //全选
        choices: false, //多选按钮
        state:3, //当前未核校状态
        currentVideoUrl: [], // 当前视频链接
        videoDialogVisible: false, 

        options: {
          autoplay: false, // 设置自动播放
          muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音
          preload: "auto", // 预加载
          controls: true, // 显示播放的控件
        },
        searchMoreType: false,
        fileList: [],
        videoList: [],
        planForm: {
          id: "",
          admission_time: "",
          reason_remark: "",
          status: "",
        },
        addSchoolPlanForm: {
          id: "",
          images: [],
          videos: [],
          description: "",
        },
        inSchoolPlan: [
          {
            value: "1",
            label: "待审核",
            id: "1",
          },
          {
            value: "2",
            label: "已审核",
            id: "2",
          },
        ],
        inSchooleVis: false,
        inSchooleTextVis: false,
        isFull: false,
        loadingPage: false,
        // 选项框选中数组
        ids: [],
  
        // 选项框非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        formInline: {
          page: 1,
          page: 1,
          per_page: 10,
        },
        pageparm: {
          page: 1,
          per_page: 10,
          total: 0,
        },
        statusList: [
          { id: 1, name: "正常" },
          { id: 0, name: "禁用" },
        ],
        timers: [],
        tableData: [],
        selectData: [],
        GroupList: [], //管理员分组列表
        planList: [
          {
            value: "1",
            label: "待制定",
            id: "1",
          },
          {
            value: "2",
            label: "已制定",
            id: "2",
          },
        ],
        isStatusList: [
          {
            value: "1",
            label: "未排课",
            id: "1",
          },
          {
            value: "2",
            label: "已排课",
            id: "2",
          },
        ],
        inSchoolPlan: [
          {
            value: "1",
            label: "待审核",
            id: "1",
          },
          {
            value: "2",
            label: "已审核",
            id: "2",
          },
        ],
        linePlanList: [
          {
            value: "1",
            label: "是",
            id: "1",
          },
          {
            value: "2",
            label: "否",
            id: "2",
          },
        ],
        images: "",
        userInfo: "", //用户权限字段
      };
    },
    methods: {
      // 检查是否存在
      inspect(e, id) {
        // 检查是否包含id
        let index = this.ids.indexOf(id);
        if (index !== -1&&!e) {
          this.ids.splice(index, 1);
        }
        if (index == -1&&e) {
          this.ids.push(id);
        } 
        if (this.ids.length ===this.tableData.length) this.checked1 = true;
        else this.checked1 = false;
      },
      change1(e) {
        //全选或者反选操作
        //console.log(e, "-----选择"); 
        let multipleTable = this.$refs.multipleTable;
        if(!multipleTable||multipleTable.length<=0) return
        // 全选or反选
        this.ids = [];
        multipleTable.forEach((item) => {
          if (e) this.ids.push(item.dataobjs.id);
          item.checked2 = e;
        });
        //console.log(this.ids, "-----this.ids");
      },
      // 关闭全选
      CloseManage() {
        this.checked1 = false; //关闭全选按钮
        this.choices = false; //关闭多选
        this.change1(false); //全部为反选
      },
      // 批量核校
      openOkAll(e) {
      const ids = this.ids;
      if (ids.length == 0) {
        this.$message.warning("请选择要重新核校的列表");
        return;
      }
      let vm = this;
      vm.$confirm("是否确认选中的数据进行批量重新核校?", "批量重新核校", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        return statuss({ ids: ids, status: 1 }).then((res) => {
          if (res.code == 1) {
            vm.$message.success(res.msg);
            vm.search();
            // vm.getData();
          } else {
            vm.$message.warning(res.msg);
          }
        });
      });
    },
    openOkAllons(e){
      let vm = this;
      vm.$confirm("是否确认选中的数据进行重新核校?", "重新核校", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        return statuss({ ids: e, status: 1 }).then((res) => {
          if (res.code == 1) {
            vm.$message.success(res.msg);
            vm.search();
            // vm.getData();
          } else {
            vm.$message.warning(res.msg);
          }
        });
      });
    },
      authority(groupArr = [0]) {
        // 权限筛选
        let userInfo = this.userInfo;
        // 当前权限和传来的权限组进行对比
        if (groupArr.some((item) => Number(item) === userInfo)) return true;
        return false;
      },
      rowUrl(url) {
        this.currentVideoUrl = url;
        this.videoDialogVisible = true; // 显示对话框
      },
      diaClose() {
        this.fileList = [];
        this.videoList = [];
      },
      searchMore() {
        this.searchMoreType = !this.searchMoreType;
      },
      search(i, e) {
          this.searchMoreType =false;
        this.formInline.page = 1;
        this.formInline.per_page = 10;
        let objs = this.$refs.RefScreen?.formInline||{};
        this.formInline = { ...this.formInline, ...objs };
        this.getData();
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handlePreview(file) {
        ////console.log(file);
      },
      loadPZip(e) {
        if (!e.images || e.images.length == 0) {
          return this.$message.error("入校照片暂未上传");
        }
  
        axios({
          url: this.$config.API_URL+"school/imageszip/", // 后端提供的 ZIP 文件下载 URL
          method: "POST",
          responseType: "blob", // 重要，这会返回一个 Blob 对象
          data: {
            id: e.id,
          },
        })
          .then((response) => {
            const url = URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
            link.download = `${e.school_name}${e.grade}${e.class_name}-图.Zip`; // 设置下载文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url); // 释放URL对象
          })
          .catch((e) => {
            //console.error("下载失败:", e);
          });
      },
      loadVZip(e) {
        if (!e.video || e.video.length == 0) {
          return this.$message.error("入校视频暂未上传！！！");
        }
        axios({
          url: this.$config.API_URL+"school/videozip/", // 后端提供的 ZIP 文件下载 URL
          method: "POST",
          responseType: "blob", // 重要，这会返回一个 Blob 对象
          data: {
            id: e.id,
          },
        })
          .then((response) => {
            const url = URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
            link.download = `${e.school_name}${e.grade}${e.class_name}-视频.Zip`; // 设置下载文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url); // 释放URL对象
          })
          .catch((e) => {
            //console.error("下载失败:", e);
          });
      },
      exportText(e) {
        if (this.ids.length == 0) {
          this.$message.error("请先选择导出数据");
          return;
        }
        axios({
          url: this.$config.API_URL+"school/export/",
          method: "post", //请求方法
          responseType: "blob", //表示接受服务器返回的二进制流
          data: {
            id: this.ids,
          },
        })
          .then((res) => {
            ////console.log(res);
  
            let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
            let fileName = "学校核销表"; // 自定义文件名
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              // IE兼容
              window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
              let objectUrl = (window.URL || window.webkitURL).createObjectURL(
                blob
              );
              let downloadLink = document.createElement("a");
              downloadLink.href = objectUrl;
              downloadLink.download = fileName;
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);
              window.URL.revokeObjectURL(objectUrl); // 释放URL对象
            }
          })
          .catch((error) => {
            this.$message.error("导出失败");
          });
      },
      handleAvatarSuccess(res, file) {
        this.fileList.push({
          name: res.data.url,
          url: res.data.url,
        });
      },
      handleAvatarSuccessVideo(res, file) {
        this.videoList.push({
          name: res.data.url,
          url: res.data.url,
        });
      },
      handleChangesImage(e) {},
      beforeAvatarUpload(file) {
        const isJPG =
          file.type === "image/jpeg" ||
          file.type === "image/jpg" ||
          file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      handleClose() {
        this.inSchooleVis = false;
        this.inSchooleTextVis = false;
      },
      submitData() {
        rstaffschoolAdd({ ...this.planForm }).then((res) => {
          if (res.code == 1) {
            this.$message({
              showClose: true,
              message: "制定成功",
              type: "success",
            });
            this.getData();
            this.inSchooleVis = false;
          }
        });
      },
  
      submitDataS() {
        this.addSchoolPlanForm.images = this.fileList.map((item) => {
          return item.url;
        });
        this.addSchoolPlanForm.videos = this.videoList.map((item) => {
          return item.url;
        });
        ////console.log(this.addSchoolPlanForm);
        addschool({ ...this.addSchoolPlanForm }).then((res) => {
          if (res.code == 1) {
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success",
            });
            this.getData();
            this.inSchooleTextVis = false;
          }
        });
      },
      planT(e) {
        this.planForm.status = this.inSchoolPlan.find(
          (item) => item.value == e
        ).value;
      },
      formatDateTime(time) {
        return dayjs.unix(time).format("YYYY-MM-DD HH:mm");
      },
      refreshData(x) {
        // 新增成功 搜索归0
        if (x) this.handleEdit("", "reset");
        else this.getData();
      },
      setFull() {
        this.isFull = !this.isFull;
        window.dispatchEvent(new Event("resize"));
      },
      // 表格序列号
      getIndex($index) {
        // (当前页 - 1) * 当前显示数据条数 + 当前行数据的索引 + 1
        return (this.pageparm.page - 1) * this.pageparm.per_page + $index + 1;
      },
      //多选项框被选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
        ////console.log(this.ids, "选中项");
      },
      /** 批量删除按钮操作 */
      handleDelete(row) {
        const ids = this.ids;
  
        if (ids.length == 0) {
          this.$message.warning("请选择要删除数据");
          return;
        }
        let vm = this;
        vm.$confirm("是否确认删除选中的数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(function () {
          return schoolDel({ ids: ids }).then((res) => {
            if (res.code == 1) {
              vm.$message.success(res.msg);
              vm.search();
            } else {
              vm.$message.warning(res.msg);
            }
          });
        });
      },
      changeStatus(row) {
        ////console.log(row, "row----");
      },
      addModule(row) {
        // 普通全部新增
        //console.log(this.$refs.multipleTable);
        ////console.log(this.GroupList, "---------新增出发");
        this.$refs.addModuleFlag.addModuleFn(row, "新增", this.GroupList);
      },
      // 在地提交学校信息
      editshows(row) {
        this.$refs.editModuleShool.addModuleFn(
          row,
          "学校信息提交",
          this.GroupList
        );
      },
      addModuleShool() {
        // 学校新增
        this.$refs.addModuleShool.addModuleFn(null, "学校新增", this.GroupList);
      },
      handleEdit(row, flag) {
        if (flag == "detail") {
          this.$refs.addModuleFlag.addModuleFn(row, "详情", this.GroupList);
        } else if (flag == "edit") {
          if (this.authority([2, 4]))
            this.$refs.addModuleShool.addModuleFn(
              row,
              this.authority([2]) ? "编辑" : "核校确认提交",
              this.GroupList
            );
          else this.$refs.addModuleFlag.addModuleFn(row, "编辑", this.GroupList);
        } else if (flag == "delete") {
          let vm = this;
          vm.$confirm("您确定要删除选中的数据吗？", {
            closeOnClickModal: false,
          })
            .then((res) => {
              schoolDel({ id: row.id }).then((res) => {
                if (res.code == 1) {
                  vm.$message.success(res.msg);
                  vm.search();
                } else {
                  vm.$message.warning(res.msg);
                }
              });
            })
            .catch(() => {});
        } else if (flag == "reset") {
          // 清空组件
          this.searchMoreType=false
          this.$refs.RefScreen.reset();
          this.formInline = {
            page: 1,
            per_page: 10,
          };
          this.pageparm = {
            page: 1,
            per_page: 10,
            total: 0,
          };
          this.getData();
        }
      },
  
      callFather(parm) {
        this.formInline.page = parm.page;
        this.formInline.per_page = parm.per_page;
        this.getData();
      },
      //获取列表
      async getData() {
        this.loadingPage = true;
        this.formInline.status = this.state;
        schoolList(this.formInline).then((res) => {
          this.loadingPage = false;
          if (res.code == 1) {
            this.tableData = res.data.data;
            // // 将列表数据转换为树形数据
            // this.tableData = XEUtils.toArrayTree(res.data.data, { parentKey: 'parent', strict: false })
            this.pageparm.page = res.data.current_page;
            this.pageparm.per_page = res.data.per_page;
            this.pageparm.total = res.data.total;
            this.CloseManage();
          }
        });
      },
  
      timeChange(val) {
        if (val) {
          this.formInline.beginAt = dateFormats(val[0], "yyyy-MM-dd hh:mm:ss");
          this.formInline.endAt = dateFormats(val[1], "yyyy-MM-dd hh:mm:ss");
        } else {
          this.formInline.beginAt = null;
          this.formInline.endAt = null;
        }
        this.search();
      },
      getGroupList() {
        // 管理员分组获取
        adminGroup().then((res) => {
          if (res.code == 1) {
            //////console.log(res, "------------成功获取到管理员分组列表");
            this.GroupList = res.data;
          }
        });
      },
      handleRemove(file, fileList) {
        this.fileList = this.fileList.filter((item) => {
          return item.name != file.name;
        });
        ////console.log(this.fileList);
      },
      handleRemoveVideo(file, fileList) {
        this.videoList = this.videoList.filter((item) => {
          return item.name != file.name;
        });
        ////console.log(this.videoList);
      },
      handlePreview(file) {
        ////console.log(file);
      },
      handleSuccess(res, file) {
        if (res.code == 1) {
          schoolImport({ file: res.data.url }).then((res) => {
            if (res.code == 1) {
              this.getData();
              this.$message.success(`导入成功`);
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      },
      handleExceed(files, fileList) {
        ////console.log(files, fileList, "111");
        return;
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        );
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      // 文件状态改变时
      handleChange(file) {
        // 结构获取文件名
        let { name } = file;
        // 正则校验文件格式
        let result = /^.xls|.png|.xlsx$/.test(
          // 截取文件名后缀 例：.zip
          // 注解：
          // substring() 截取字符串中介于两个指定下标之间的字符
          // toLowerCase()  将字符串转换为小写
          // lastIndexOf(".") 返回一个指定的字符串值最后出现的位置
          name.substring(name.lastIndexOf(".")).toLowerCase()
        );
        if (!result) {
          this.$message.error("上传文件格式不符合要求");
          return;
        }
      },
      // 制定计划
      order(e) {
        this.inSchooleVis = true;
        this.planForm.id = e.id;
      },
      // 添加入校资料
      addPlan(e) {
        if (e.images) {
          this.fileList = e.images.map((item, index) => {
            return {
              name: `${e.city}${e.county}-${e.school_name}${e.grade}${
                e.class_name
              }-${e.course}照片-${index + 1}`,
              url: item,
            };
          });
        }
        if (e.video) {
          this.videoList = e.video.map((item, index) => {
            return {
              name: `${e.city}${e.county}-${e.school_name}${e.grade}${
                e.class_name
              }-${e.course}视频-${index + 1}`,
              url: item,
            };
          });
        }
        this.inSchooleTextVis = true;
        this.addSchoolPlanForm.id = e.id;
      },
    },
    created() {
      this.userInfo = Number(JSON.parse(getStorage("groupId"))); //权限
  
      // 获取管理员分组
      this.getGroupList();
      // 数据获取
      this.getData();
    },
  };
  </script>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .video-box {
    width: 100%;
    max-width: 500px;
    max-height: 500px;
  }
  ::v-deep .video-js .vjs-big-play-button {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  </style>
  